package com.zz.dao;

import com.zz.pojo.Book;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class BookDao {
    public void initTable(){
        //加载配置，得到工厂
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myjpa");
        entityManagerFactory.close();
    }
    //添加
    public void add(){
        //加载配置，得到工厂
        EntityManagerFactory myjpa = Persistence.createEntityManagerFactory("myjpa");
        //得到实体管理对象
        EntityManager entityManager = myjpa.createEntityManager();
        //开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        //操作数据
        Book book=new Book();
        book.setBookName("紫樽大人传");
        book.setBookAuthor("小紫樽");
        book.set(2L);
        book.setBookDetail("记载了紫樽大人传奇的一生。。。。");
        entityManager.persist(book);
        //提交事务
        transaction.commit();
        //关闭连接
        entityManager.close();
        myjpa.close();
    }

    public static void main(String[] args) {
        BookDao bo=new BookDao();
        //bo.initTable();//在数据库生成对应的表和关联表
        bo.add();
    }
}
